from Client import create_clients
from settings import LTC_BOT_NAME
from time import sleep
import asyncio
from Console import console


async def for_one(client, BOT_NAME, send_money=False, proxy=None):
    if proxy:
        client.set_proxy(proxy)

    await client.start()

    dialog = None
    for dlg in await client.get_dialogs():
        if dlg.title == BOT_NAME:
            dialog = dlg
    if not dialog:
        return 0

    await client.send_message(BOT_NAME, '/balance')

    sleep(3)
    msgs = await client.get_messages(dialog, limit=1)
    cur = 0
    sleep(3)
    try:
        for mes in msgs:
            str_a = str(mes.message)
            zz = str_a.replace('Available balance: ', '')
            qq = zz.replace(' LTC', '')
            console.send_notification(str(client.phone_number) + ' - ' + qq)
            cur = float(qq)
            if send_money and cur > 0.0001:
                await client.send_message(BOT_NAME, '/withdraw')
                sleep(2)
                await client.send_message(BOT_NAME, client.wallet)
                sleep(1)
                console.send_alert("Sending {} LTC from {} to {} wallet".format(cur, client.phone_number, client.wallet))
                await client.send_message(BOT_NAME, str(cur))
                sleep(1)
                await client.send_message(BOT_NAME, "✔️ Confirm")

                cur = 0
    except Exception as e:
        console.send_critical("Error occurred: {}".format(e))
        cur = 0
        
    await client.disconnect()
    return cur


async def send_total_balance(client, total):
    await client.connect()
    await client.notify_admins("Total LTC: {}".format(total))
    await client.disconnect()


async def check_balance():
    clients = create_clients()

    total = 0

    for i in range(len(clients)):


        cur = await for_one(clients[i], BOT_NAME=LTC_BOT_NAME)

        total += cur
        sleep(1)
    await send_total_balance(clients[0], "Total LTC: {}".format(total))
    console.send_notification("Total: {}".format(total))


if __name__ == '__main__':
    asyncio.run(check_balance())
